<script setup lang='ts'>
import { ref, onMounted, computed } from 'vue'
import { NInput, NCard, NSpace, NButton, NDrawer, NDrawerContent, NTabs, NTabPane } from 'naive-ui'
import Markdown from 'vue3-markdown-it';
import 'highlight.js/styles/github.css';

const { t } = useI18n()

// 搜索框的值
const searchValue = ref('')

// 文件列表数据
const items = ref([])
// 保存原始文件列表数据（用于搜索后恢复）
const originalItems = ref([])
// 搜索状态
const searchStatus = ref('')
// 搜索结果数量
const searchResultCount = ref(0)

// 控制drawer显示的变量
const showDetailDrawer = ref(false)

// 当前选中的项目
const selectedItem = ref({ id: 0, title: '', description: '', content: '', url: '' })

// 获取文件列表
const fetchFiles = async () => {
  try {

    //console.log("11111111111111111111111111111111111111111111111111111111");

    const response = await fetch('http://192.168.1.5:5000/api/files');
    const files = await response.json();

    //console.log(files)

    // 检查是否有错误
    if (files.error) {
      console.error('获取文件列表失败:', files.error);
      return;
    }

    // 转换数据格式以匹配现有结构，并反转数组顺序（后生成的显示在前面）
    const mappedFiles = files.map((file, index) => ({
      id: index + 1,
      title: file.name,
      description: `文件路径: ${file.url}`,
      url: file.url
    })).reverse();
    
    // 更新显示列表和原始数据备份
    items.value = mappedFiles;
    originalItems.value = [...mappedFiles];
    
    // 重置搜索状态
    searchStatus.value = '';
    searchResultCount.value = mappedFiles.length;
  } catch (error) {
    console.error('获取文件列表失败:', error);
  }
}

// 处理搜索
const handleSearch = () => {
  // 如果搜索框为空，恢复原始列表
  if (!searchValue.value.trim()) {
    items.value = [...originalItems.value];
    searchStatus.value = '';
    searchResultCount.value = items.value.length;
    return;
  }
  
  console.log('搜索:', searchValue.value);
  
  // 添加实际的搜索逻辑 - 更灵活的搜索（标题和描述）
  const searchTerm = searchValue.value.toLowerCase();
  const filteredItems = originalItems.value.filter(item =>
    item.title.toLowerCase().includes(searchTerm) || 
    item.description.toLowerCase().includes(searchTerm)
  );
  
  // 更新搜索结果
  items.value = filteredItems;
  searchResultCount.value = filteredItems.length;
  
  // 更新搜索状态
  if (filteredItems.length === 0) {
    searchStatus.value = '未找到匹配结果';
  } else {
    searchStatus.value = `找到 ${filteredItems.length} 个匹配结果`;
  }
}

// 获取文件扩展名
const getFileExtension = (filename) => {
  return filename.split('.').pop().toLowerCase();
}

// 处理查看按钮点击事件
const handleViewDetails = async (item) => {
  const fileExtension = getFileExtension(item.title);

  // 对于HTML文件，直接提供URL进行渲染
  if (fileExtension === 'html') {
    selectedItem.value = {
      id: item.id,
      title: item.title,
      description: 'HTML文件预览：',
      content: '',
      url: item.url,
      type: 'html'
    };
    showDetailDrawer.value = true;
    return;
  }

  try {
    // 从后端获取文件内容
    const response = await fetch(`http://192.168.1.5:5000/api/files/${item.title}`);
    const fileData = await response.json();

    // 检查是否有错误
    if (fileData.error) {
      console.error('获取文件内容失败:', fileData.error);
      selectedItem.value = {
        id: item.id,
        title: item.title,
        description: '无法加载文件内容',
        content: fileData.error,
        url: item.url,
        type: 'error'
      };
      showDetailDrawer.value = true;
      return;
    }

    // 根据文件类型设置显示类型
    let type = 'text';
    if (fileExtension === 'md' || fileExtension === 'markdown') {
      type = 'markdown';
    }

    selectedItem.value = {
      id: item.id,
      title: fileData.name,
      description: '文件内容如下：',
      content: fileData.content,
      url: item.url,
      type: type
    };
    showDetailDrawer.value = true;
  } catch (error) {
    console.error('获取文件内容失败:', error);
    selectedItem.value = {
      id: item.id,
      title: item.title,
      description: '无法加载文件内容',
      content: '',
      url: item.url,
      type: 'error'
    };
    showDetailDrawer.value = true;
  }
}

// 计算属性：处理Markdown中的图片路径
const processedMarkdownContent = computed(() => {
  if (selectedItem.value.type !== 'markdown') return '';

  // 处理相对路径的图片，将其转换为完整的URL
  const baseUrl = window.location.origin;
  return selectedItem.value.content.replace(
    /\(([^)]*\.(png|jpg|jpeg|gif|svg))\)/gi,
    `(http://192.168.1.5:5000/detection-data/$1)`
  );
});

// 组件挂载时获取文件列表
onMounted(() => {
  fetchFiles();
});
</script>

<template>
  <div class="container">
     <!-- 修改搜索框 -->
    <div class="search-box mb-4">
      <n-input v-model:value="searchValue" type="text" placeholder="搜索..." clearable style="width: 50%" @keyup.enter="handleSearch" />
      <n-button type="primary" @click="handleSearch" class="ml-2">搜索</n-button>
      <n-button type="primary" @click="fetchFiles" class="ml-2">刷新</n-button>
      <span v-if="searchStatus" class="search-status ml-2">{{ searchStatus }}</span>
    </div>

    <!-- 大的容器框 -->
    <n-card :title="`异常检测报告 (${searchResultCount})`" class="main-container">
      <n-space vertical>
        <!-- 一条一条的小框 -->
        <n-card
          v-for="item in items"
          :key="item.id"
          class="item-box"
          hoverable
        >
          <div class="flex justify-between items-center">
            <span>{{ item.title }}</span>
            <n-button type="primary" size="small" @click="handleViewDetails(item)">查看</n-button>
          </div>
        </n-card>
      </n-space>
    </n-card>

    <!-- 新增：查看详细信息的drawer -->
    <n-drawer v-model:show="showDetailDrawer" :width="'80%'" placement="right">
      <n-drawer-content closable>
        <template #header>
          <h3>{{ selectedItem.title }}</h3>
        </template>
        <n-tabs type="segment">
          <n-tab-pane name="content" tab="内容">
            <div v-if="selectedItem.type === 'html'">
              <p>{{ selectedItem.description }}</p>
              <iframe
                :src="selectedItem.url"
                style="width: 100%; height: 600px; border: 1px solid #ccc;"
                title="HTML Preview"
              ></iframe>
            </div>
            <div v-else-if="selectedItem.type === 'markdown'" class="markdown-content">
              <p>{{ selectedItem.description }}</p>
              <Markdown :source="processedMarkdownContent" />
            </div>
            <div v-else-if="selectedItem.type === 'text'">
              <p>{{ selectedItem.description }}</p>
              <pre style="white-space: pre-wrap; word-wrap: break-word; background-color: #f5f5f5; padding: 10px; border-radius: 4px;">{{ selectedItem.content }}</pre>
            </div>
            <div v-else-if="selectedItem.type === 'error'">
              <p>{{ selectedItem.description }}</p>
              <p style="color: red;">{{ selectedItem.content }}</p>
            </div>
            <div v-else>
              <p>不支持的文件类型</p>
            </div>
          </n-tab-pane>
          <n-tab-pane name="raw" tab="原始内容">
            <p>原始文件内容：</p>
            <pre style="white-space: pre-wrap; word-wrap: break-word; background-color: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 600px; overflow-y: auto;">{{ selectedItem.content }}</pre>
          </n-tab-pane>
          <n-tab-pane name="download" tab="下载">
            <n-button type="primary" tag="a" :href="selectedItem.url" target="_blank" download>
              下载文件
            </n-button>
            <p style="margin-top: 10px;">点击按钮下载原始文件以保留完整格式</p>
          </n-tab-pane>
        </n-tabs>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<style scoped lang='scss'>
.container {
  padding: 20px;
}

.search-box {
  display: flex;
  align-items: center;
}

.search-status {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}

// 自定义按钮颜色
:deep(.n-button--primary-type) {
  background-color: #5CADFF !important;
  border-color: #5CADFF !important;
}

.main-container {
  min-height: 500px;
}

.item-box {
  margin-bottom: 10px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  max-height: 600px;
  overflow-y: auto;
}

// Markdown样式
.markdown-content {
  padding: 10px;

  :deep(img) {
    max-width: 100%;
    height: auto;
  }

  :deep(pre) {
    background-color: #f5f5f5;
    padding: 10px;
    border-radius: 4px;
    overflow-x: auto;

    code {
      background-color: transparent;
      padding: 0;
    }
  }

  :deep(code) {
    background-color: #f5f5f5;
    padding: 2px 4px;
    border-radius: 4px;
  }

  :deep(blockquote) {
    border-left: 4px solid #ddd;
    padding-left: 16px;
    margin-left: 0;
    color: #666;
  }

  :deep(table) {
    border-collapse: collapse;
    width: 100%;

    th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }

    th {
      background-color: #f5f5f5;
    }
  }
}
</style>
